package com.jnu.myaccount.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.jnu.myaccount.AccountFragment;
import com.jnu.myaccount.BankFragment;
import com.jnu.myaccount.R;
import com.jnu.myaccount.data.Money;

import java.util.ArrayList;
import java.util.List;

public class AccountActivity extends AppCompatActivity implements AccountFragment.FragmentInteraction{

    private String[] tabTitles=new String[2];
    private List<Fragment> mDatas=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);
        getSupportActionBar().hide();
        tabTitles= new String[]{"收支","转账"};
        mDatas.add(AccountFragment.newInstance());
        mDatas.add(BankFragment.newInstance());

        ViewPager2 viewPagerFragments=findViewById(R.id.viewPager2_content);
        viewPagerFragments.setAdapter(new MyFragmentAdapter(this));

        TabLayout tabLayoutHeader=findViewById(R.id.tabLayout_header);
        TabLayoutMediator tabLayoutMediator=new TabLayoutMediator(tabLayoutHeader, viewPagerFragments, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(tabTitles[position]);
            }
        });
        tabLayoutMediator.attach();

        //创建返回事件
        ImageButton returnButton=findViewById(R.id.return_button);
        returnButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void process(Money money,int position){
        if(money!=null){
            Intent intent=new Intent();
            intent.putExtra("money",money);
            intent.putExtra("position",position);
            setResult(1,intent);
            finish();
        }
    }
    private class MyFragmentAdapter extends FragmentStateAdapter {

        public MyFragmentAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return mDatas.get(position);
        }

        @Override
        public int getItemCount() {
            return 2;
        }
    }
}